import { exec } from 'child_process';
import fs from 'fs';
import path from 'path';

const SECRET = '909689902';
const LOG_DIR = path.join(process.cwd(), 'logs');
const LOG_FILE = path.join(LOG_DIR, 'webhook.log');

if (!fs.existsSync(LOG_DIR)) { fs.mkdirSync(LOG_DIR, { recursive: true }); }

function log(message) {
  const now = new Date();
  const timeStr = `${now.getFullYear()}.${String(now.getMonth() + 1).padStart(2, '0')}.${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
  fs.appendFileSync(LOG_FILE, `[${timeStr}] ${message}\n`);
}

export async function POST({ request }) {
  const token = request.headers.get('x-gitee-token');
  if (token !== SECRET) {
    log(`❌ Secret 错误，拒绝访问，错误的密钥是 ${token}`);
    return new Response('Forbidden', { status: 403 });
  }
  setTimeout(() => {
    const deployScriptPath = path.join(process.cwd(), 'deploy.sh');
    exec(`sh ${deployScriptPath}`, (err, stdout, stderr) => {
      if (err) { log(`❌ 部署失败: ${err.message}`); }
      log(`✅ 部署成功:\n${stdout}`);
      if (stderr) { log(`⚠️ 警告信息:\n${stderr}`); }
    });
  }, 0);
  return new Response('Webhook received, deploying...');
}
